package com.io.vo;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * The class/interface
 *
 * @author guod
 * @version 1.0 use jdk 1.8
 */
@Data
public class TreeNode {
    private Integer id;
    private Integer pid;
    private String nodeName;
    private String icon;
    private List<TreeNode> children;

    public static List<TreeNode> buildTree(List<TreeNode> nodes) {
        Map<Integer, List<TreeNode>> sub = nodes.stream()
                .filter(node -> node.getPid() != 0)
                .collect(Collectors.groupingBy(TreeNode::getPid));
        nodes.forEach(node -> node.setChildren(sub.get(node.getId())));
        return nodes.stream().filter(node -> node.getPid() == 0).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<TreeNode> treeNodes = new ArrayList<>();
        TreeNode treeNode = new TreeNode();
        treeNode.setId(1);
        treeNode.setPid(0);
        treeNodes.add(treeNode);

        TreeNode treeNode1 = new TreeNode();
        treeNode1.setId(2);
        treeNode1.setPid(1);
        treeNodes.add(treeNode1);
        System.out.println(treeNodes);
        System.out.println(buildTree(treeNodes));
    }
}


